package com.smart.translator.ui.home;

import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.smart.translator.data.model.Language;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

public class HomeViewModel extends AndroidViewModel {
    private static final String LANG_CACHE_KEY = "allLanguages";
    private static final String PREFS_NAME = "home_prefs";
    private static final String OTHER_LANG_INDEX_KEY = "otherLangIndex";
    private static final String MY_LANG_INDEX_KEY = "myLangIndex";
    private static final String MIC_INDEX_KEY = "micIndex";
    private static final String VOICE_INDEX_KEY = "voiceIndex";

    private final MutableLiveData<List<Language>> otherLangOptions = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<List<Language>> myLangOptions = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<Integer> otherLangIndex = new MutableLiveData<>(0);
    private final MutableLiveData<Integer> myLangIndex = new MutableLiveData<>(0);
    private final MutableLiveData<List<String>> micOptions = new MutableLiveData<>(Arrays.asList("手机麦克风", "系统内录"));
    private final MutableLiveData<Integer> micIndex = new MutableLiveData<>(0);
    private final MutableLiveData<List<String>> voiceOptions = new MutableLiveData<>(Arrays.asList("男声", "女声"));
    private final MutableLiveData<Integer> voiceIndex = new MutableLiveData<>(0);
    private final MutableLiveData<String> version = new MutableLiveData<>("V1.0.0");
    private final MutableLiveData<String> timeLeft = new MutableLiveData<>("12小时 24分钟");
    private final MutableLiveData<String> balance = new MutableLiveData<>("25¥");
    private final MutableLiveData<String> error = new MutableLiveData<>("");
    private final MutableLiveData<String> translateResult = new MutableLiveData<>("");
    private TextToSpeech tts;
    private final SharedPreferences prefs;

    public HomeViewModel(@NonNull Application application) {
        super(application);
        prefs = application.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        tts = new TextToSpeech(application, status -> {
            if (status != TextToSpeech.ERROR) {
                tts.setLanguage(Locale.CHINESE);
            }
        });
        loadPrefs();
        loadLanguages();
    }

    private void loadPrefs() {
        otherLangIndex.setValue(prefs.getInt(OTHER_LANG_INDEX_KEY, 0));
        myLangIndex.setValue(prefs.getInt(MY_LANG_INDEX_KEY, 0));
        micIndex.setValue(prefs.getInt(MIC_INDEX_KEY, 0));
        voiceIndex.setValue(prefs.getInt(VOICE_INDEX_KEY, 0));
    }

    private void savePref(String key, int value) {
        prefs.edit().putInt(key, value).apply();
    }

    private void loadLanguages() {
        // 先尝试本地缓存
        String cache = prefs.getString(LANG_CACHE_KEY, null);
        if (cache != null) {
            setLangOptionsFromJson(cache);
        }
        // 拉取最新
        new Thread(() -> {
            try {
                // 获取服务器地址
                String serverUrl = getServerUrl();
                
                URL url = new URL("http://" + serverUrl + "/languages");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(3000);
                conn.setReadTimeout(3000);
                int code = conn.getResponseCode();
                if (code == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) sb.append(line);
                    reader.close();
                    String json = sb.toString();
                    prefs.edit().putString(LANG_CACHE_KEY, json).apply();
                    setLangOptionsFromJson(json);
                }
            } catch (Exception ignored) {}
        }).start();
    }
                    // 保存到本地缓存
    private void setLangOptionsFromJson(String json) {
        try {
            JSONArray arr = new JSONArray(json);
            List<Language> list = new ArrayList<>();
            for (int i = 0; i < arr.length(); i++) {
                JSONObject obj = arr.getJSONObject(i);
                list.add(new Language(obj.optString("code"), obj.optString("name")));
            }
            new Handler(Looper.getMainLooper()).post(() -> {
                otherLangOptions.setValue(list);
                myLangOptions.setValue(list);
            });
        } catch (Exception ignored) {}
                
    }
    
    /**
     * 获取服务器地址
     */
    private String getServerUrl() {
        try {
            android.content.SharedPreferences prefs = getApplication().getSharedPreferences("app_config", Context.MODE_PRIVATE);
            return prefs.getString("server_url", "qixin.yeshan.fun");
        } catch (Exception e) {
            Log.e("HomeViewModel", "获取服务器地址失败", e);
            return "qixin.yeshan.fun";
        }
    }

    public LiveData<List<Language>> getOtherLangOptions() { return otherLangOptions; }
    public LiveData<List<Language>> getMyLangOptions() { return myLangOptions; }
    public LiveData<Integer> getOtherLangIndex() { return otherLangIndex; }
    public LiveData<Integer> getMyLangIndex() { return myLangIndex; }
    public LiveData<List<String>> getMicOptions() { return micOptions; }
    public LiveData<Integer> getMicIndex() { return micIndex; }
    public LiveData<List<String>> getVoiceOptions() { return voiceOptions; }
    public LiveData<Integer> getVoiceIndex() { return voiceIndex; }
    public LiveData<String> getVersion() { return version; }
    public LiveData<String> getTimeLeft() { return timeLeft; }
    public LiveData<String> getBalance() { return balance; }
    public LiveData<String> getError() { return error; }
    public LiveData<String> getTranslateResult() { return translateResult; }

    public void setOtherLangIndex(int idx) { 
        otherLangIndex.setValue(idx); 
        savePref(OTHER_LANG_INDEX_KEY, idx);
        Log.d("HomeViewModel", "设置对方语言索引: " + idx);
    }
    
    public void setMyLangIndex(int idx) { 
        myLangIndex.setValue(idx); 
        savePref(MY_LANG_INDEX_KEY, idx);
        Log.d("HomeViewModel", "设置我的语言索引: " + idx);
    }
    public void setMicIndex(int idx) { micIndex.setValue(idx); savePref(MIC_INDEX_KEY, idx); }
    public void setVoiceIndex(int idx) { voiceIndex.setValue(idx); savePref(VOICE_INDEX_KEY, idx); }

    public void onQrClick() {
        error.setValue("二维码功能开发中");
    }
    public void onAdClick() {
        error.setValue("广告功能开发中");
    }

    public void translate(String text) {
        if (text == null || text.trim().isEmpty()) {
            error.setValue("请输入要翻译的内容");
            return;
        }
        new Thread(() -> {
            try {
                // 获取服务器地址
                String serverUrl = getServerUrl();
                
                JSONObject req = new JSONObject();
                req.put("text", text.trim());
                String from_lang = otherLangOptions.getValue() != null && otherLangIndex.getValue() != null ?
                        otherLangOptions.getValue().get(otherLangIndex.getValue()).getCode() : "";
                String to_lang = myLangOptions.getValue() != null && myLangIndex.getValue() != null ?
                        myLangOptions.getValue().get(myLangIndex.getValue()).getCode() : "";
                req.put("from_lang", from_lang);
                req.put("to_lang", to_lang);
                URL url = new URL("http://" + serverUrl + "/translate");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);
                conn.getOutputStream().write(req.toString().getBytes());
                int code = conn.getResponseCode();
                if (code == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) sb.append(line);
                    reader.close();
                    JSONObject resp = new JSONObject(sb.toString());
                    if (resp.has("result") && resp.getJSONObject("result").has("trans_result")) {
                        String dst = resp.getJSONObject("result").getJSONObject("trans_result").optString("dst", "");
                        new Handler(Looper.getMainLooper()).post(() -> translateResult.setValue(dst));
                    } else {
                        new Handler(Looper.getMainLooper()).post(() -> translateResult.setValue("翻译失败"));
                    }
                } else {
                    new Handler(Looper.getMainLooper()).post(() -> translateResult.setValue("翻译失败"));
                }
            } catch (Exception e) {
                new Handler(Looper.getMainLooper()).post(() -> translateResult.setValue("翻译失败"));
            }
        }).start();
    }

    public void playTranslation() {
        if (tts != null && translateResult.getValue() != null) {
            tts.speak(translateResult.getValue(), TextToSpeech.QUEUE_FLUSH, null, null);
        }
    }
    public void copyTranslation() {
        String text = translateResult.getValue();
        if (text != null && !text.isEmpty()) {
            ClipboardManager clipboard = (ClipboardManager) getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("翻译结果", text);
            clipboard.setPrimaryClip(clip);
            Toast.makeText(getApplication(), "已复制", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onCleared() {
        if (tts != null) tts.shutdown();
        super.onCleared();
    }
} 